package com.leetcode;

public class AddTwoNumbers
{
	public ListNode add2Numbers(ListNode l1, ListNode l2)
	{
		ListNode p = new ListNode(0);
		ListNode store = null;
		if (l1 == null || l2 == null)
		{// 判断是否有空节点
			if (l2 != null)
			{
				store = l2;
			}
			if (l1 != null)
			{
				store = l1;
			}
			return store;
		}
		store = p;// store存储头节点
		int sum = l1.val + l2.val;
		int c = sum / 10;// c为进位数
		store.val = sum % 10;
		l1 = l1.next;
		l2 = l2.next;
		while (l1 != null || l2 != null)
		{
			p.next = new ListNode(0);
			p = p.next;
			if (l1 == null)
			{
				sum = l2.val + c;
				l2 = l2.next;
			}
			else if (l2 == null)
			{
				sum = l1.val + c;
				l1 = l1.next;
			}
			else
			{
				sum = l1.val + l2.val + c;
				l1 = l1.next;
				l2 = l2.next;
			}
			if (sum > 9)
			{
				p.val = sum % 10;
				c = sum / 10;
			}
			else
			{
				c = 0;
				p.val = sum;
			}
		}
		if (c != 0)
		{
			p.next = new ListNode(c);
		}
		return store;
	}

	class ListNode
	{
		private ListNode next;
		private int val;

		public ListNode(int x)
		{
			val = x;
			next = null;
		}
	}
}
